import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_learn_vi/src/bean/bean_video_category.dart';
import 'package:flutter_learn_vi/src/net/dio_utils.dart';
import 'package:flutter_learn_vi/src/page/common/common_nodata_widget.dart';
import 'package:flutter_learn_vi/src/page/study/search_widget.dart';
import 'package:flutter_learn_vi/src/page/study/video_request_page.dart';
import 'package:flutter_learn_vi/src/page/study/video_serarch_page.dart';
import 'package:flutter_learn_vi/src/utils/navigator_utils.dart';

import 'main_study_data_page.dart';

/// 创建人： Created by zhaolong
/// 创建时间：Created by  on 2021/1/13.
///
/// 可关注公众号：我的大前端生涯   获取最新技术分享
/// 可关注网易云课堂：https://study.163.com/instructor/1021406098.htm
/// 可关注博客：https://blog.csdn.net/zl18603543572
///
/// 代码清单
///代码清单
class VideoStudyMainV2Page extends StatefulWidget {
  /// 0 首页进入 不显示搜索
  final int pageIndex;
  final int taskId;

  const VideoStudyMainV2Page({Key key, this.pageIndex = 1, this.taskId})
      : super(key: key);

  @override
  _VideoStudyMainV2PageState createState() => _VideoStudyMainV2PageState();
}

///当前页面被装载在[PageView]中，使用KeepAlive使用页面保持状态
class _VideoStudyMainV2PageState extends State<VideoStudyMainV2Page>
    with AutomaticKeepAliveClientMixin {
  //页面保持状态
  @override
  bool get wantKeepAlive => true;

  //左侧分类
  List<BeanVideoCategory> _categoryList = [];

  //当前选中的左侧分类
  BeanVideoCategory _currentLeftBean;

  @override
  void initState() {
    super.initState();
    Future.delayed(Duration.zero, () {
      getVideoCourseCategory();
    });
  }

  Future<bool> getVideoCourseCategory() async {
    Map<String, dynamic> map = Map();
    //post请求发送
    ResponseInfo responseInfo = await DioUtils.instance.getRequest(
      url: HttpHelper.videoCategoryUrl,
      queryParameters: map,
    );
    if (responseInfo.success) {
      List list = responseInfo.data;
      _categoryList = [];
      list.forEach((element) {
        BeanVideoCategory beanVideoCategory =
            BeanVideoCategory.fromMap(element);
        _categoryList.add(beanVideoCategory);
      });
      if (_categoryList.length == 1) {
        _currentLeftBean = _categoryList[0];
        _currentLeftBean.isSelect = true;
      } else if (_categoryList.length > 1) {
        _currentLeftBean = _categoryList[1];
        _currentLeftBean.isSelect = true;
      }
    } else {
      if (responseInfo.code == 401) {
        //关闭首页面
      } else {
        NavigatorUtils.pop(context);
      }
    }
    if (mounted) {
      setState(() {});
    }
    return Future.value(true);
  }

  ///代码清单 13-55
  ///分类选择页面 状态栏相关设置
  ///lib/src/page/home/home_good_class_widget.dart
  @override
  Widget build(BuildContext context) {
    super.build(context);
    //设置状态栏的颜色 有AppBar时，会被覆盖
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        elevation: 1,
        leading: InkWell(
          onTap: () {
            NavigatorUtils.pop(context);
          },
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Container(
                height: 26,
                width: 26,
                child: Icon(
                  Icons.close,
                  color: Colors.red,
                  size: 18,
                ),
                decoration: BoxDecoration(
                    border: Border.all(color: Colors.red),
                    borderRadius: BorderRadius.all(Radius.circular(44))),
              )
            ],
          ),
        ),
        title: buildHeaderContainer(),
      ),
      body: buildScaffold(),
    );
  }

  int _rankType = 0;

  Container buildHeaderContainer() {
    return Container(
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          InkWell(
            onTap: () {
              _rankType = 0;
              setState(() {});
            },
            child: Container(
              alignment: Alignment.center,
              padding: EdgeInsets.only(left: 8, right: 8, top: 4, bottom: 4),
              child: Text(
                "在线学习",
                style: TextStyle(
                    color: _rankType == 0 ? Colors.white : Colors.red,
                    fontSize: 14,
                    fontWeight: FontWeight.w500),
              ),
              decoration: BoxDecoration(
                color: _rankType == 0 ? Colors.red : Colors.white,
                border: Border.all(color: Colors.red),
                borderRadius: BorderRadius.all(Radius.circular(6)),
              ),
            ),
          ),
          // InkWell(
          //   onTap: () {
          //     _rankType = 1;
          //     setState(() {});
          //   },
          //   child: Container(
          //     alignment: Alignment.center,
          //     padding: EdgeInsets.only(left: 8, right: 8, top: 4, bottom: 4),
          //     child: Text(
          //       "学习资料",
          //       style: TextStyle(
          //           color: _rankType == 1 ? Colors.white : Colors.grey,
          //           fontSize: 14,
          //           fontWeight: FontWeight.w500),
          //     ),
          //     decoration: BoxDecoration(
          //       color: _rankType == 1 ? Colors.red : Colors.white,
          //       border: Border.all(color: Colors.red),
          //       borderRadius: BorderRadius.only(
          //         topRight: Radius.circular(6),
          //         bottomRight: Radius.circular(6),
          //       ),
          //     ),
          //   ),
          // ),
        ],
      ),
    );
  }

  ///代码清单 13-56
  ///分类选择页面 页面主体
  ///lib/src/page/home/home_good_class_widget.dart
  buildScaffold() {
    if (widget.pageIndex == 0) {
      return Container(
          color: Colors.white,
          padding: EdgeInsets.only(top: 12),
          child: buildClassListRow());
    }
    return buildAnimatedSwitcher();
  }

  AnimatedSwitcher buildAnimatedSwitcher() {
    return AnimatedSwitcher(
      //动画执行切换时间
      duration: const Duration(milliseconds: 400),
      //动画构建器 构建指定动画类型
      transitionBuilder: (Widget child, Animation<double> animation) {
        //执行缩放动画
        return FadeTransition(child: child, opacity: animation);
      },

      ///执行动画的子 Widget
      ///只有子 Widget 被切换时才会触发动画
      child: buildMainWidget(),
    );
  }

  buildMainWidget() {
    if (_rankType == 0) {
      return buildClassListColumn();
    }
    return buildStudyData();
  }

  Widget buildClassListColumn() {
    return Column(
      children: [
        //标题部分
        Container(
            height: 40,
            margin: EdgeInsets.only(left: 12, right: 12, top: 10, bottom: 10),
            child: GestureDetector(
                onTap: () {
                  NavigatorUtils.pushPage(context, VideoSearchPage());
                },
                child: SearchWidget())),
        //分类列表部分
        Expanded(
          child: Container(
            padding: EdgeInsets.only(top: 0),
            child: buildClassListRow(),
          ),
        )
      ],
    );
  }

  ///代码清单 13-57
  ///分类选择页面 左右列表 1:3 比例适配
  ///lib/src/page/home/home_good_class_widget.dart
  Widget buildClassListRow() {
    if (_categoryList == null || _categoryList.length == 0) {
      return NoDataWidget(
        text: "暂无数据",
      );
    }
    return Row(
      children: [
        Expanded(
          flex: 2,
          child: Container(
            decoration: BoxDecoration(
                color: Colors.grey[200],
                borderRadius: BorderRadius.only(topRight: Radius.circular(12))),
            //左侧列表
            child: buildLeftListView(),
          ),
        ),
        Expanded(
          flex: 5,
          //圆角
          child: ClipRRect(
            borderRadius: BorderRadius.all(Radius.circular(10)),
            //右侧列表
            child: VideoItemRequestPage(
              taskId: widget.taskId,
              itemBean: _currentLeftBean,
              key: UniqueKey(),
            ),
          ),
        )
      ],
    );
  }

  int _selectIndex = 1;

  ///代码清单 13-58
  ///分类选择页面 左侧分类列表
  ///lib/src/page/home/home_good_class_widget.dart
  buildLeftListView() {
    return ListView.builder(
      padding: EdgeInsets.zero,
      itemCount: _categoryList.length,
      itemBuilder: (BuildContext context, int index) {
        //获取当前选中的分类
        BeanVideoCategory classBean = _categoryList[index];
        //选中的分类使用白色底色
        BoxDecoration boxDecoration = BoxDecoration(color: Colors.grey[200]);
        if (index == _selectIndex) {
          boxDecoration = BoxDecoration(color: Colors.white);
        } else if (index == _selectIndex - 1) {
          if (index == 0) {
            boxDecoration = BoxDecoration(
                color: Colors.grey[200],
                borderRadius: BorderRadius.only(
                    topRight: Radius.circular(12),
                    bottomRight: Radius.circular(12)));
          } else {
            boxDecoration = BoxDecoration(
                color: Colors.grey[200],
                borderRadius:
                    BorderRadius.only(bottomRight: Radius.circular(12)));
          }
        } else if (index == _selectIndex + 1) {
          boxDecoration = BoxDecoration(
              color: Colors.grey[200],
              borderRadius: BorderRadius.only(topRight: Radius.circular(12)));
        } else {
          if (index == 0) {
            boxDecoration = BoxDecoration(
                color: Colors.grey[200],
                borderRadius: BorderRadius.only(topRight: Radius.circular(12)));
          }
        }
        Color textColor = Color(0xff666666);
        Widget leftWidget = Container();
        if (classBean.isSelect) {
          textColor = Color(0xff333333);
          leftWidget = Container(
            width: 6,
            height: 23,
            decoration: BoxDecoration(
                color: Colors.green,
                borderRadius: BorderRadius.only(
                    topRight: Radius.circular(6),
                    bottomRight: Radius.circular(6))),
          );
        }

        return InkWell(
          onTap: () {
            //如果当前点击的类目为选中状态
            //就不做任何操作
            if (classBean.isSelect) {
              return;
            }
            //设置其他的状态为未选中
            _categoryList.forEach((element) {
              element.isSelect = false;
            });
            //设置当前类目为选中
            classBean.isSelect = true;
            //更新
            _currentLeftBean = classBean;
            _selectIndex = index;
            //刷新状态
            setState(() {});
          },
          child: Container(
            color: Colors.white,
            child: Container(
              alignment: Alignment.center,
              height: 60,
              decoration: boxDecoration,
              child: Row(
                children: [
                  leftWidget,
                  Expanded(
                    child: Text(
                      "${classBean.categoryName}",
                      textAlign: TextAlign.center,
                      style: TextStyle(color: textColor),
                    ),
                  )
                ],
              ),
            ),
          ),
        );
      },
    );
  }

  buildStudyData() {
    return StudyDataPage();
  }
}
